<?php		
	require_once ("./General/dbConnection.php");
	require_once ("./General/validate.php");
	require_once("./Model/m_Logger.php");
	
	class LoginHandler {
	private $m_username = 'username';
	private $m_error = "error";
	private $my_database;
	
	public function __construct() {
		$this->my_database = new DBConnection(); 
		$this->my_database->Connect();
		$this->m_error = new m_Logger;
	}
	
	
	//Funktion som kontrollerar ifall användaren redan är inloggad. 
	//Inloggad = True
	public function IsLoggedIn()
	{
		if (isset($_SESSION[$this->m_username])){
			return true;
		}
		if (isset($_COOKIE['user'])){
		$user = $_COOKIE['user'];
		
		$db = new DBConnection();
		$db->Connect();
		$sql = "SELECT TemporaryPassword FROM users WHERE Username = ?";
		$stmt = $db->prepare($sql);
		$stmt->bind_param("s", $user);
		if ($stmt === FALSE) {
            return false;
        }
        $stmt->execute();
		$stmt->bind_result($tmpPwd);
		$stmt->fetch();
		$stmt->close();
		if (isset($_COOKIE['password'])== $tmpPwd){
			return true;			 	
		}
		return false;
		}

    	return false;
	}
	public function DoLoginDB($User, $Password){
		$db = new DBConnection();
		$db->Connect();
				if (mysqli_connect_errno()) {
			$this->m_error->setLogError("uppkoppling misslyckades");
    		exit();
		}
		$sql = "SELECT COUNT(*) FROM users WHERE Username = ?";
		$stmt = $db->prepare($sql);
		$stmt->bind_param("s", $User);
		if ($stmt === FALSE) {
            return false;
        }
        $stmt->execute();
		$stmt->store_result();
		$numrows = $stmt->num_rows;
		$stmt->close();

		if($numrows == 1) {
			$sql = "SELECT Password FROM users WHERE Username = ?";
			$stmt = $db->prepare($sql);
			$stmt->bind_param("s", $User);
			if ($stmt === FALSE) {
	            return false;
	        }
	        $stmt->execute();
			$stmt->bind_result($pwdMatch);
			$stmt->fetch();
			$stmt->close();
				$Password = sha1($Password);
				if($pwdMatch == $Password){
					$_SESSION[$this->m_username] = $User;
					return true;
				}
		}
		
		
		return false;
	}
	
	public function DoLogout()
	{
		if(!isset($_SESSION)) {
	 		session_start();
			return false;
		}
		unset($_SESSION[$this->m_username]);
		return true;
	}
	
	public function GetTmpPwd($User){
		//$pass = 'TemporaryPassword';
		$temppass = sha1(time()*time()*time());

		$db = new DBConnection();
		$db->Connect();
		$sql = "UPDATE users SET TemporaryPassword= ? WHERE Username= ?";
        $stmt = $db->prepare($sql);
		$temppass = sha1($temppass);           
        $stmt->bind_param("ss", $temppass, $User);
        if ($stmt === FALSE) {
            return false;
        }
	    $stmt->execute();                 
		$stmt->close(); 
        return $temppass;
	}
	public function WhoIsLoggedOn(){
		if(!isset($_SESSION)) {
			 		session_start();
		}
		$user = $_SESSION[$this->m_username];
		return $user;
	}
	}	


